﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using RentAWorker.Business.Interfaces;
using RentAWorker.Business.Impl.Util;
using Dal = RentAWorker.DataAccess.Interfaces;
using Entities = RentAWorker.DataAccess.Entities;
using RentAWorker.Business.DTO;
using RentAWorker.DataAccess.Interfaces;
using RentAWorker.DataAccess.Entities;
using System.ServiceModel.Activation;
using System.Security.Permissions;

namespace RentAWorker.Business.Impl
{
    [AspNetCompatibilityRequirements(RequirementsMode=AspNetCompatibilityRequirementsMode.Allowed)]
    public class ManageRequestFacade : IManageRequestService
    {
        private Dal.IRentalServiceAccess RentAccess;

        public ManageRequestFacade()
        {
            RentAccess = DataAccessFactory.GetRentalServiceAccess();
        }

        #region IManageRequestService Members

        [PrincipalPermission(SecurityAction.Demand, Role = "AccountManager")]
        public RentalService[] GetRentalServicesForManager(string status)
        {
            IEnumerable<Entities.RentalService> Services = 
                RentAccess.GetRentalServicesByState(status, DateTime.MinValue, DateTime.MaxValue);

            List<RentalService> Response = new List<RentalService>();
            foreach (var s in Services)
            {
                Response.Add(s);
            }
            return Response.ToArray();
        }

        [PrincipalPermission(SecurityAction.Demand, Role = "AccountManager")]
        public void ApproveRentalService(int rentalServiceId)
        {
            UpdateRentalServiceState(rentalServiceId, "Accepted");
        }

        [PrincipalPermission(SecurityAction.Demand, Role = "AccountManager")]
        public void RejectRentalService(int rentalServiceId)
        {
            UpdateRentalServiceState(rentalServiceId, "Declined");
        }

        #endregion

        #region Private Helper Methods

        private void UpdateRentalServiceState(int rentalServiceId, string state)
        {
            Entities.RentalService Service = RentAccess.GetRentalService(rentalServiceId);
            if (Service == null)
                throw new InvalidOperationException(string.Format("Rental service with ID {0} does not exist!", rentalServiceId));

            // Find the "approved" state
            Service.RentalServiceState = RentAccess.GetRentalServiceStates().Single
                                            (s =>
                                             string.Compare(s.RentalServiceStateName, state, true) == 0);
        }

        #endregion
    }
}
